
package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhu.location.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.PreferenceKeys;
import com.zhu.salesmanagement.common.PreferenceStore;
import com.zhu.salesmanagement.models.DataCenter;
import com.zhu.salesmanagement.models.VerifyUserResult;
import com.zhu.salesmanagement.network.ParseData;
import com.zhu.salesmanagement.network.PostMethod;
import com.zhu.salesmanagement.network.XMLRPCMethod;
import com.zhu.salesmanagement.network.XMLRPCMethodCallback;
import com.zhu.salesmanagement.utils.DialogUtil;
import com.zhu.salesmanagement.utils.Util;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class UserLoginActivity extends Activity {

    private final static int LOGIN_DIALOG = 0;

    private final static String REMEBER = "1";
    private Handler mHander = new Handler();
    private EditText usernameTxt, passwordTxt, ipText;
    private CheckBox mCheckBox = null;
    private TextView mClewTextView = null;
    private Handler updateHandler = new Handler();
    private int DELAY_APP_START = 2000;

    private boolean kFirstRunningLoginActivity = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        /*
         * getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
         * WindowManager.LayoutParams.FLAG_FULLSCREEN);
         */
        if (kFirstRunningLoginActivity) {
            // run mUpdateTimeTask after 2 seconds
            updateHandler.postDelayed(mUpdateTimeTask, DELAY_APP_START);
            setContentView(R.layout.layout_splash);
            kFirstRunningLoginActivity = false;
        } else {
            updateHandler.post(applicationStart);
        }
    }

    private Runnable applicationStart = new Runnable() {
        public void run() {

            setupViews();

            initLocalData();
        }
    };

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            updateHandler.post(applicationStart);
        }
    };

    private void initLocalData() {
        String username = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME,
                "");
        String password = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_PASSWORD,
                "");

        String remeber = PreferenceStore.getInstance(UserLoginActivity.this).getString(PreferenceKeys.KEY_REMEBER, "");
        if(remeber.equals(REMEBER)){
            usernameTxt.setText(username);
            passwordTxt.setText(password);
        }
    }

    private void setupViews() {
        setContentView(R.layout.activity_user_login);
        usernameTxt = (EditText) this.findViewById(R.id.username_field);
        passwordTxt = (EditText) this.findViewById(R.id.password_field);
        ipText = (EditText) this.findViewById(R.id.id_field);
        mCheckBox = (CheckBox) findViewById(R.id.savepassword);
        mClewTextView = (TextView)findViewById(R.id.clewtext);
        Button submitBtn = (Button) this.findViewById(R.id.login_button);
        submitBtn.setOnClickListener(buttonClickListener);
    }

    private OnClickListener buttonClickListener = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_button:
                doLogin();
                break;
            default:
                break;
        }
    }
    };

    /**
     * Do Login
     */
    private void doLogin() {
        if (!Actions.isNetwork(this)) {
            Actions.alertShowDetails(this, getString(R.string.tips_label),
                    getString(R.string.network_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(UserLoginActivity.this,
                                    Settings.ACTION_WIRELESS_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });

        } else {
            String username = usernameTxt.getText().toString().trim();
            String password = passwordTxt.getText().toString().trim();
            if (username.length() == 0 || password.length() == 0) {
                inputNotCorrect();
            } else {
            	String lastname = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME, "");
            	if(!lastname.equals(username) && lastname.length() > 0){
            		inputMoreUsername();
            		return;
            	}
                doLogin(username, password);
            }
        }

    }

    private void inputNotCorrect() {
        mHander.post(new Runnable() {
            public void run() {
                DialogUtil.getSimpleDialog(UserLoginActivity.this, "",
                        getString(R.string.username_password_not_empty), null).show();
            }
        });
    }

    private void inputMoreUsername() {
        mHander.post(new Runnable() {
            public void run() {
                DialogUtil.getSimpleDialog(UserLoginActivity.this, "",
                        getString(R.string.loginfailed), null).show();
            }
        });
    }

    protected void jump2MainActivity() {
        Intent tent = new Intent(UserLoginActivity.this, AddStoreActivity.class);
        UserLoginActivity.this.startActivity(tent);
        UserLoginActivity.this.finish();
    }

    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case LOGIN_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.doing_login)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;

            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void doLogin(String name, String password) {
        // jump2MainActivity();
        // if(mCheckBox.isChecked()){
        // PreferenceStore.getInstance(UserLoginActivity.this).putString(PreferenceKeys.KEY_USERNAME,
        // usernameTxt.getText().toString().trim());
        // PreferenceStore.getInstance(UserLoginActivity.this).putString(PreferenceKeys.KEY_PASSWORD,
        // passwordTxt.getText().toString().trim());
        // }

        String text = ipText.getText().toString().trim();
        if(ipText.getVisibility() == View.VISIBLE && text != null && text.length() > 0){
            SalesApplication.mApplicaton.setXMLRPCClient(text);
        }

        boolean isFirst = true;
        String lastname = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME, "");
        if(lastname.length() > 1){
            isFirst = false;
        }
        //Util.isFirst = isFirst;
        showDialog(LOGIN_DIALOG);
        PostMethod.requesLogin(name, password, isFirst, Util.getVerName(this), new XMLRPCMethodCallback() {
            public void callFinished(int status, Object result) {
                doResult(ParseData.parseLogin(result));
            }
        },
                SalesApplication.mApplicaton.getXMLRPCClient());
    }

    private void doResult(final VerifyUserResult result) {
        mHander.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                dismissDialog(LOGIN_DIALOG);
                if (result == null || result.status == 0) {
                    if(Util.canOfflineLogin(UserLoginActivity.this)){
                        popOfflineLoginDialog();
                    }else{
                        DialogUtil.getSimpleDialog(UserLoginActivity.this,
                                getString(R.string.notice_label),
                                getString(R.string.login_unknow_error), null).show();
                    }
                } else {
                    if (mCheckBox.isChecked()) {
                    	 PreferenceStore.getInstance(UserLoginActivity.this).putString(
                                 PreferenceKeys.KEY_REMEBER, REMEBER);
                    } else {
                    	PreferenceStore.getInstance(UserLoginActivity.this).putString(
                                PreferenceKeys.KEY_REMEBER, "");
                    }
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_USERNAME,
                            usernameTxt.getText().toString().trim());
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_PASSWORD,
                            passwordTxt.getText().toString().trim());
                    Util.mVerifyUserResult = result;
                    jump2MainActivity();
                }
            }
        });
    }

    private void popOfflineLoginDialog(){
        VerifyUserResult result = new VerifyUserResult();
        result.name = "";
        result.isNeedUpdate = false;
        result.mDecVersion = Util.getVerName(this);
        result.iGPSInterval = 120;
        result.isOffline = true;
        Util.mVerifyUserResult = result;

        Actions.alertShowDetails(this, this.getString(R.string.notice_label),
                this.getString(R.string.login_unknow_error),
                R.string.queding, R.string.offlinelogin,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        jump2MainActivity();
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_MENU) {
//            SalesApplication.mApplicaton.changeXMLRPCClient();
            if(ipText.getVisibility() == View.VISIBLE){
                ipText.setVisibility(View.GONE);
            }else{
                ipText.setVisibility(View.VISIBLE);
            }
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_BACK) {
            this.finish();
            return true;
        }
        return false;
    }
}
